package com.seadragon.app.ksr.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.seadragon.app.ksr.model.Business;
import com.seadragon.app.ksr.model.Customer;
import com.seadragon.app.ksr.model.CustomerEventSubscription;
import com.seadragon.app.ksr.model.Event;
import com.seadragon.app.ksr.model.EventSchedule;
import com.seadragon.app.ksr.model.KsrConstants;
import com.seadragon.app.ksr.service.BusinessService;
import com.seadragon.app.ksr.service.CustomerService;
import com.seadragon.app.ksr.service.EventScheduleService;
import com.seadragon.app.ksr.service.EventService;
import com.seadragon.app.ksr.util.GsonUtils;

@Controller
public class EventJsonController {
	
	private static Logger logger = LoggerFactory.getLogger(LoginController.class);

	@Autowired
	private BusinessService businessService;
	
	@Autowired
	private CustomerService customerService;
	
	@Autowired
	private EventService eventService;
	
	@Autowired
	private EventScheduleService eventScheduleService;
	
	//================== find event/event-schedules from customer side =================//
	
	@RequestMapping(value = "/customer/event/{eventId}/get.json", method = RequestMethod.GET)
	public @ResponseBody
	String getEventById(HttpServletRequest request, HttpSession session,@PathVariable long eventId) {
		Event event = eventService.findById(eventId);
		String json = null;
		if (event!=null)
			json =GsonUtils.ObjectToGson(event);
		return json;
	}
	
	@RequestMapping(value = "/customer/event-schedule/{eventId}/list.json", method = RequestMethod.GET)
	public @ResponseBody
	String getEventScheduleListByEventId(HttpServletRequest request, HttpSession session,@PathVariable long eventId) {
		String eventJson=getEventById(request, session, eventId);
		return EventScheduleListJson(eventJson,null,null);
	}
	
	@RequestMapping(value = "/customer/event-schedule/{eventId}/list/{offset}/{pagesize}.json", method = RequestMethod.GET)
	public @ResponseBody
	String getEventScheduleListByEventIdInPagination(HttpServletRequest request, HttpSession session,@PathVariable long eventId,@PathVariable Integer offset,@PathVariable Integer pagesize) {
		String eventJson=getEventById(request, session, eventId);
		return EventScheduleListJson(eventJson,offset,pagesize);
	}

	
	//============== business ===================
	@RequestMapping(value = "/business/event/list/{offset}/{pagesize}.json", method = RequestMethod.GET)
	public @ResponseBody
	String getEventListJson2(HttpServletRequest request, HttpSession session,@PathVariable Integer offset,@PathVariable Integer pagesize) {
		return EventListJson((Business)session.getAttribute(KsrConstants.SESSION_SCOPED_BUSINESS), offset, pagesize);
	}
	
	@RequestMapping(value = "/business/event/list.json", method = RequestMethod.GET)
	public @ResponseBody
	String getEventListJson(HttpServletRequest request, HttpSession session) {
		return EventListJson((Business)session.getAttribute(KsrConstants.SESSION_SCOPED_BUSINESS), null, null);
	}
	
	
	@RequestMapping(value = "/business/event/{businessId}/list/{offset}/{pagesize}.json", method = RequestMethod.GET)
	public @ResponseBody
	String getEventListJson5(HttpServletRequest request, HttpSession session,@PathVariable int businessId,@PathVariable Integer offset,@PathVariable Integer pagesize) {
		return EventListJson(businessService.findById(businessId), offset, pagesize);
	}
	
	@RequestMapping(value = "/business/event/{businessId}/list.json", method = RequestMethod.GET)
	public @ResponseBody
	String getEventListJsonByBusiness(HttpServletRequest request, HttpSession session,@PathVariable int businessId) {
		return EventListJson(businessService.findById(businessId), null, null);
	}
	
	
	private String EventListJson (Business business,Integer offset,Integer pagesize){
		String json = null;
		List<Event> events = null;
		if (business != null) {
			events = eventService.findAllEventsBy(business);
		} 
		if (events!=null)
			json =GsonUtils.ObjectToGson(events);
		return json;
	}
	

	//============== event schedule list ===================

	@RequestMapping(value = "/business/event-schedule/list/{offset}/{pagesize}.json", method = RequestMethod.POST)
	public @ResponseBody
	String geteventlistjson5(HttpServletRequest request, HttpSession session,@RequestBody String eventJson,@PathVariable Integer offset,@PathVariable Integer pagesize) {
		return EventScheduleListJson(eventJson, offset, pagesize);
	}
	
	@RequestMapping(value = "/business/event-schedule/list.json", method = RequestMethod.POST)
	public @ResponseBody
	String getEventScheduleListJsonByBusiness(HttpServletRequest request, HttpSession session,@RequestBody String eventJson) {
		return EventScheduleListJson(eventJson, null, null);
	}
	
	
	private String EventScheduleListJson (String eventJson,Integer offset,Integer pagesize){
		String json = null;
		List<EventSchedule> schedules = null;
		
		if (StringUtils.isNotEmpty(eventJson)) {
			Event event = (Event)GsonUtils.GsonToObject(eventJson, Event.class);
			schedules = eventScheduleService.findAllEventSchedulesBy(event);
		} 
		if (schedules!=null)
			json =GsonUtils.ObjectToGson(schedules);
		return json;
	}	
	
	//save an event
	@RequestMapping(value = "/business/event/save.json", method = RequestMethod.POST)
	@ResponseBody
	public JSONObject createEvent(@RequestBody String eventJson,HttpSession session) {
		logger.debug(eventJson);
		JSONObject json = new JSONObject();
		Event event = (Event)GsonUtils.GsonToObject(eventJson, Event.class);
		Business business = (Business )session.getAttribute(KsrConstants.SESSION_SCOPED_BUSINESS);
		// save event
		if (business!=null&&business.getId()==event.getBusiness().getId()){
			if (event.getId()>0){
				eventService.update(event);
			} else {
				eventService.save(event);
			}
			json.put("status", "ok");
		} else {
			json.put("status","error:unauthorized action");
		}
		
		return json;
	}
	


	
	//create an eventSchedule
	@RequestMapping(value = "/business/event-schedule/save.json", method = RequestMethod.POST)
	@ResponseBody
	public JSONObject createEventSchedule(@RequestBody String esjson,HttpSession session) {
		logger.debug(esjson);
		EventSchedule eventSchedule = (EventSchedule)GsonUtils.GsonToObject(esjson, EventSchedule.class);
		// save eventSchedule
		if (eventSchedule.getId()>0){
			eventScheduleService.update(eventSchedule);
		} else {
			eventScheduleService.save(eventSchedule);
		}
		
		JSONObject json = new JSONObject();
		json.put("status", "ok");
		return json;
	}
	
	
	//create an event subscription
	@RequestMapping(value = "/customer/event-subscription/save.json", method = RequestMethod.POST)
	@ResponseBody
	public JSONObject createEventSubscription(@RequestBody String esjson,HttpSession session) {
		logger.debug(esjson);
		CustomerEventSubscription subscription = (CustomerEventSubscription)GsonUtils.GsonToObject(esjson, CustomerEventSubscription.class);
		// save event subscription
		if (subscription.getId()>0){
			customerService.update(subscription);
		} else {
			customerService.subscribe(subscription);
		}
		
		JSONObject json = new JSONObject();
		json.put("status", "ok");
		return json;
	}
	
// get customer subscription list
	
	@RequestMapping(value = "/customer/event-subscription/list/{offset}/{pagesize}.json", method = RequestMethod.GET)
	public @ResponseBody
	String getSubscriptionListJson2(HttpServletRequest request, HttpSession session,@PathVariable Integer offset,@PathVariable Integer pagesize) {
		return subscriptionListJson((Customer)session.getAttribute(KsrConstants.SESSION_SCOPED_CUSTOMER), offset, pagesize);
	}
	
	@RequestMapping(value = "/customer/event-subscription/list.json", method = RequestMethod.GET)
	public @ResponseBody
	String getSubscriptionListJson(HttpServletRequest request, HttpSession session) {
		return subscriptionListJson((Customer)session.getAttribute(KsrConstants.SESSION_SCOPED_CUSTOMER), null, null);
	}
	
	@RequestMapping(value = "/customer/event-subscription/list/{eventId}.json", method = RequestMethod.GET)
	public @ResponseBody
	String getSubscriptionListJsonByCustomerAndEvent(HttpServletRequest request, HttpSession session,@PathVariable long eventId) {
		Customer customer = (Customer)session.getAttribute(KsrConstants.SESSION_SCOPED_CUSTOMER);
		if (customer!=null){
			return getSubscriptionListJsonByCustomerAndEvent1(request, session, customer.getId(), eventId);
		}
		return null;
	}
	
	@RequestMapping(value = "/customer/event-subscription/list/{customerId}/{eventId}.json", method = RequestMethod.GET)
	public @ResponseBody
	String getSubscriptionListJsonByCustomerAndEvent1(HttpServletRequest request, HttpSession session,@PathVariable long customerId,@PathVariable long eventId) {
		String json = null;
		Event event =eventService.findById(eventId);
		Customer customer = customerService.findById(customerId);
		List<CustomerEventSubscription> subscriptionList = null;
		if (event!=null&&customer!=null){
			subscriptionList = customerService.findBy(customer, event);
			if (subscriptionList!=null)
				json =GsonUtils.ObjectToGson(subscriptionList);
		}
		return json;
	}
	
	
	@RequestMapping(value = "/customer/event-subscription/{customerId}/list/{offset}/{pagesize}.json", method = RequestMethod.GET)
	public @ResponseBody
	String getSubscriptionListJson5(HttpServletRequest request, HttpSession session,@PathVariable int customerId,@PathVariable Integer offset,@PathVariable Integer pagesize) {
		return subscriptionListJson(customerService.findById(customerId), offset, pagesize);
	}
	
	@RequestMapping(value = "/customer/event-subscription/{customerId}/list.json", method = RequestMethod.GET)
	public @ResponseBody
	String getSubscriptionListJsonByBusiness(HttpServletRequest request, HttpSession session,@PathVariable int customerId) {
		return subscriptionListJson(customerService.findById(customerId), null, null);
	}
	
	
	private String subscriptionListJson (Customer customer,Integer offset,Integer pagesize){
		String json = null;
		List<CustomerEventSubscription> subscriptionList = null;
		if (customer != null) {
			if (offset!=null&&pagesize!=null)
				subscriptionList = customerService.findAllSubscriptions(customer,offset,pagesize);
			else
				subscriptionList = customerService.findAllSubscriptions(customer);
		} 
		if (subscriptionList!=null)
			json =GsonUtils.ObjectToGson(subscriptionList);
		return json;
	}
	
	@RequestMapping(value = "/customer/event-subscription/remove.json", method = RequestMethod.POST)
	public @ResponseBody
	JSONObject removeSubscriptionById(HttpServletRequest request, HttpSession session,@RequestBody String subscriptionjson) {
		JSONObject json = new JSONObject();
		Customer customer = (Customer)session.getAttribute(KsrConstants.SESSION_SCOPED_CUSTOMER);
		CustomerEventSubscription subscription =  (CustomerEventSubscription)GsonUtils.GsonToObject(subscriptionjson, CustomerEventSubscription.class);
		if (subscription!=null&&customer!=null&&subscription.getCustomer().getId()==customer.getId()){
			customerService.unsubscribe(subscription);
			json.put("status", "ok");
		} else {
			json.put("status", "failed");
			json.put("errMsg", "illegal action!");
		}
		return json;
	}	
	
}

